<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElTable, ElTableColumn, ElButton, ElDialog, ElForm, ElFormItem, ElInput, ElDatePicker, ElMessageBox, ElMessage } from 'element-plus'
import CommonLayout from '../components/CommonLayout.vue'
import SupplierSelect from '../components/SupplierSelect.vue'
import MaterialSelect from '../components/MaterialSelect.vue'
import { Search, Plus, Edit, Delete, Check, Close, Filter, Refresh, Download, InfoFilled } from '@element-plus/icons-vue'
import { apiRequest } from '../utils/apiRequest'

// 采购到货单数据
const purchaseReceipts = ref([])
const loading = ref(false)
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)

// 搜索条件
const searchParams = reactive({
  receiptCode: '',
  purchaseOrderCode: '',
  supplierId: '',
  status: '',
  startDate: '',
  endDate: ''
})

// 供应商列表
const suppliers = ref([])
const purchaseOrders = ref([])
const materials = ref([])
const warehouses = ref([])

// 对话框状态
const dialogVisible = ref(false)
const detailDialogVisible = ref(false)
const dialogType = ref('create') // 'create' 或 'update'
const currentReceipt = ref({
  id: '',
  receiptCode: '',
  purchaseOrderId: '',
  supplierId: '',
  receiptDate: '',
  warehouseId: '',
  remark: '',
  items: [] as any[]
})

// 到货单状态映射
const statusMap = {
  0: '待审核',
  1: '已审核',
  2: '已驳回'
}

// 格式化状态
const formatStatus = (row, column, cellValue) => {
  return statusMap[cellValue]
}

// 获取采购到货单列表
const fetchPurchaseReceipts = async () => {
  loading.value = true
  try {
    const response = await apiRequest.get('/api/PurchaseReceipts', {
      params: {
        page: currentPage.value,
        pageSize: pageSize.value,
        ...searchParams
      }
    })
    // 检查响应格式并适配
    if (response.items && response.total) {
      // 分页格式响应
      purchaseReceipts.value = response.items || []
      total.value = response.total || 0
    } else if (Array.isArray(response)) {
      // 直接返回数组
      purchaseReceipts.value = response
      total.value = response.length
    } else {
      // 默认处理
      purchaseReceipts.value = []
      total.value = 0
    }
  } catch (error) {
    const errorMsg = error.response?.data?.message || '获取采购到货单列表失败'
    ElMessage.error(errorMsg)
    console.error('Failed to get purchase receipts:', error)
  } finally {
    loading.value = false
  }
}

// 获取供应商列表
const fetchSuppliers = async () => {
  try {
    console.log('Starting to fetch suppliers...')
    // 添加分页参数
    const response = await apiRequest.get('/api/suppliers', {
      params: {
        page: 1,
        pageSize: 100
      }
    })
    console.log('Suppliers API response:', response)
    
    // 处理不同格式的响应
    let suppliersData = []
    if (response?.items && response?.total) {
      // 分页格式响应
      // 检查items是否有$values属性
      suppliersData = response.items?.$values || response.items || []
    } else if (response?.$values) {
      // 带有$values属性的响应
      suppliersData = response.$values || []
    } else if (Array.isArray(response)) {
      // 直接返回数组
      suppliersData = response
    } else {
      // 默认处理
      suppliersData = []
    }
    
    console.log('Processed suppliers data:', suppliersData)
    suppliers.value = suppliersData
    
    // 检查是否有数据
    if (suppliers.value.length === 0) {
      console.log('No suppliers data available')
      ElMessage.info('没有找到供应商数据，请先创建供应商')
    } else {
      console.log('Suppliers count:', suppliers.value.length)
    }
  } catch (error) {
    const errorMsg = error.response?.data?.message || '获取供应商列表失败'
    ElMessage.error(errorMsg)
    console.error('Failed to get suppliers:', error)
    // 显示错误详情
    console.error('Error details:', error.response)
  }
}

// 获取采购订单列表
const fetchPurchaseOrders = async () => {
  try {
    console.log('Starting to fetch purchase orders...')
    // 添加分页参数
    const response = await apiRequest.get('/api/PurchaseOrders', {
      params: {
        page: 1,
        pageSize: 100
      }
    })
    console.log('Purchase orders API response:', response)
    
    // 处理不同格式的响应
    let ordersData = []
    if (response?.items && response?.total) {
      // 分页格式响应
      ordersData = response.items || []
    } else if (response?.$values) {
      // 带有$values属性的响应
      ordersData = response.$values || []
    } else if (Array.isArray(response)) {
      // 直接返回数组
      ordersData = response
    } else {
      // 默认处理
      ordersData = []
    }
    
    console.log('Processed purchase orders data:', ordersData)
    purchaseOrders.value = ordersData
    
    // 检查是否有数据
    if (purchaseOrders.value.length === 0) {
      console.log('No purchase orders data available')
      ElMessage.info('没有找到采购订单数据，请先创建采购订单')
    } else {
      console.log('Purchase orders count:', purchaseOrders.value.length)
    }
  } catch (error) {
    const errorMsg = error.response?.data?.message || '获取采购订单列表失败'
    ElMessage.error(errorMsg)
    console.error('Failed to get purchase orders:', error)
    // 显示错误详情
    console.error('Error details:', error.response)
  }
}

// 获取物料列表
const fetchMaterials = async () => {
  try {
    console.log('Starting to fetch materials...')
    const response = await apiRequest.get('/api/materials')
    console.log('Materials API response:', response)
    
    // 提取$values属性
    const materialsData = response?.$values || response || []
    console.log('Processed materials data:', materialsData)
    materials.value = materialsData
    
    // 查看第一个物料对象的属性
    if (materials.value.length > 0) {
      console.log('First material:', materials.value[0])
      console.log('First material JSON:', JSON.stringify(materials.value[0]))
      console.log('Material has materialName:', 'materialName' in materials.value[0])
      console.log('Material has specification:', 'specification' in materials.value[0])
    } else {
      console.log('No materials data available')
    }
  } catch (error) {
    const errorMsg = error.response?.data?.message || '获取物料列表失败'
    ElMessage.error(errorMsg)
    console.error('Failed to get materials:', error)
  }
}

// 获取仓库列表
const fetchWarehouses = async () => {
  try {
    const response = await apiRequest.get('/api/warehouses')
    warehouses.value = response || []
  } catch (error) {
    const errorMsg = error.response?.data?.message || '获取仓库列表失败'
    ElMessage.error(errorMsg)
    console.error('Failed to get warehouses:', error)
  }
}

// 搜索采购到货单
const handleSearch = () => {
  currentPage.value = 1
  fetchPurchaseReceipts()
}

// 重置搜索条件
const handleReset = () => {
  Object.keys(searchParams).forEach(key => {
    searchParams[key as keyof typeof searchParams] = ''
  })
  currentPage.value = 1
  fetchPurchaseReceipts()
}

// 打开对话框
const openDialog = (type: 'create' | 'update', receipt: any = {}) => {
  dialogType.value = type
  if (type === 'create') {
    resetReceiptForm()
    // 检查是否有采购订单数据
    if (purchaseOrders.value.length === 0) {
      ElMessageBox.confirm('当前没有采购订单数据，是否前往创建采购订单？', '提示', {
        confirmButtonText: '前往创建',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 导航到采购订单页面
        window.location.href = '/purchase/order'
      }).catch(() => {
        // 取消操作
      })
      return
    }
  } else {
    // 深拷贝到货单数据避免直接修改原数据
    currentReceipt.value = JSON.parse(JSON.stringify(receipt))
    // 转换日期格式
    if (currentReceipt.value.receiptDate) {
      currentReceipt.value.receiptDate = new Date(currentReceipt.value.receiptDate)
    }
  }
  dialogVisible.value = true
}

// 重置到货单表单
const resetReceiptForm = () => {
  currentReceipt.value = {
    id: '',
    receiptCode: '',
    purchaseOrderId: '',
    supplierId: '',
    supplierName: '',
    receiptDate: new Date(),
    warehouseId: '',
    remark: '',
    items: [] as any[]
  }
}

// 查看到货单详情
const viewReceiptDetail = async (id: string) => {
  try {
    const response = await apiRequest.get(`/api/PurchaseReceipts/${id}`)
    currentReceipt.value = response
    detailDialogVisible.value = true
  } catch (error) {
    ElMessage.error('获取到货单详情失败')
    console.error('Failed to get receipt detail:', error)
  }
}

// 添加到货明细
const addReceiptItem = () => {
  const newItem = {
    lineNo: currentReceipt.value.items.length + 1,
    materialId: '',
    materialName: '',
    specification: '',
    unit: '',
    purchaseQuantity: 0,
    receiptQuantity: 0,
    qualifiedQuantity: 0,
    unqualifiedQuantity: 0,
    unqualifiedReason: ''
  }
  
  currentReceipt.value.items.push(newItem)
  // 自动聚焦到新添加的行
  nextTick(() => {
    const lastIndex = currentReceipt.value.items.length - 1
    // 这里可以添加自动聚焦逻辑，如果有需要
  })
}

// 移除到货明细
const removeReceiptItem = (index: number) => {
  currentReceipt.value.items.splice(index, 1)
  // 更新行号
  currentReceipt.value.items.forEach((item, idx) => {
    item.lineNo = idx + 1
  })
}

// 当选择采购订单时，自动加载订单明细
const handlePurchaseOrderChange = async (orderId: string) => {
  if (!orderId) return
  
  try {
    const response = await apiRequest.get(`/api/PurchaseOrders/${orderId}`)
    const order = response
    
    // 清空现有明细
    currentReceipt.value.items = []
    
    // 添加订单明细到到货单
    if (order.items && order.items.length > 0) {
      order.items.forEach((item: any, index: number) => {
        currentReceipt.value.items.push({
          lineNo: index + 1,
          materialId: item.materialId,
          materialName: item.materialName,
          specification: item.specification,
          unit: item.unit,
          purchaseQuantity: item.quantity,
          receiptQuantity: 0,
          qualifiedQuantity: 0,
          unqualifiedQuantity: 0,
          unqualifiedReason: ''
        })
      })
    }
    
    // 设置供应商
    currentReceipt.value.supplierId = order.supplierId
    // 查找并设置供应商名称，确保显示正确
    const selectedSupplier = suppliers.value.find(s => s.id === order.supplierId)
    if (selectedSupplier) {
      currentReceipt.value.supplierName = selectedSupplier.supplierName
    }
    
    // 强制更新UI
    nextTick(() => {
      // 触发重新渲染
      currentReceipt.value = { ...currentReceipt.value }
    })
  } catch (error) {
    ElMessage.error('加载采购订单明细失败')
    console.error('Failed to load purchase order items:', error)
  }
}

// 处理供应商选择变化
const handleSupplierChange = (supplierId: string) => {
  // 查找并设置供应商名称
  const selectedSupplier = suppliers.value.find(s => s.id === supplierId)
  if (selectedSupplier) {
    currentReceipt.value.supplierName = selectedSupplier.supplierName
  }
}

// 处理搜索栏供应商选择变化
const handleSearchSupplierChange = () => {
  // 确保搜索参数正确更新
  searchParams.supplierId = searchParams.supplierId || ''
}

// 当选择物料时，自动填充物料信息
const handleMaterialChange = (item: any, materialId: string) => {
  if (!materialId) return
  
  const material = materials.value.find(m => m.id === materialId)
  if (material) {
    item.materialName = material.materialName
    item.specification = material.specification
    item.unit = material.unit
  }
}

// 保存采购到货单
const saveReceipt = async () => {
  // 表单验证
  if (!currentReceipt.value.purchaseOrderId) {
    ElMessage.warning('请选择采购订单')
    return
  }
  if (!currentReceipt.value.supplierId) {
    ElMessage.warning('请选择供应商')
    return
  }
  if (!currentReceipt.value.receiptDate) {
    ElMessage.warning('请选择到货日期')
    return
  }
  if (!currentReceipt.value.warehouseId) {
    ElMessage.warning('请选择入库仓库')
    return
  }
  if (currentReceipt.value.items.length === 0) {
    ElMessage.warning('请添加到货明细')
    return
  }

  // 验证每个明细行
  for (const item of currentReceipt.value.items) {
    if (!item.materialId) {
      ElMessage.warning('请选择物料')
      return
    }
    if (item.receiptQuantity <= 0) {
      ElMessage.warning('到货数量必须大于0')
      return
    }
    if (item.receiptQuantity > item.purchaseQuantity) {
      ElMessage.warning('到货数量不能大于采购数量')
      return
    }
    if (item.qualifiedQuantity < 0) {
      ElMessage.warning('合格数量不能小于0')
      return
    }
    if (item.unqualifiedQuantity < 0) {
      ElMessage.warning('不合格数量不能小于0')
      return
    }
    if (item.qualifiedQuantity + item.unqualifiedQuantity !== item.receiptQuantity) {
      ElMessage.warning('合格数量与不合格数量之和必须等于到货数量')
      return
    }
    if (item.unqualifiedQuantity > 0 && !item.unqualifiedReason) {
      ElMessage.warning('请填写不合格原因')
      return
    }
  }

  try {
    if (dialogType.value === 'create') {
      await apiRequest.post('/api/PurchaseReceipts', currentReceipt.value)
      ElMessage.success('创建采购到货单成功')
    } else {
      await apiRequest.put(`/api/PurchaseReceipts/${currentReceipt.value.id}`, currentReceipt.value)
      ElMessage.success('更新采购到货单成功')
    }
    dialogVisible.value = false
    fetchPurchaseReceipts()
  } catch (error) {
    const errorMsg = error.response?.data?.message || (dialogType.value === 'create' ? '创建采购到货单失败' : '更新采购到货单失败')
    ElMessage.error(errorMsg)
    console.error(`${dialogType.value === 'create' ? 'Creating' : 'Updating'} purchase receipt failed:`, error)
  }
}

// 删除采购到货单
const handleDelete = async (id: string) => {
  try {
    const confirmResult = await ElMessageBox.confirm(
      '确定要删除此采购到货单吗？此操作不可撤销！',
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    if (confirmResult === 'confirm') {
      await apiRequest.delete(`/api/PurchaseReceipts/${id}`)
      ElMessage.success('删除采购到货单成功')
      fetchPurchaseReceipts()
    }
  } catch (error) {
    if (error !== 'cancel') {
      const errorMsg = error.response?.data?.message || '删除采购到货单失败'
      ElMessage.error(errorMsg)
      console.error('Failed to delete purchase receipt:', error)
    }
  }
}

// 审核采购到货单
const handleApprove = async (id: string) => {
  try {
    const remark = await ElMessageBox.prompt('请输入审核意见', '审核采购到货单', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputPlaceholder: '请输入审核意见'
    })
    
    if (remark.value) {
      // 实际应用中，审核人应该从当前登录用户获取
      const approverId = '1' // 临时使用1作为用户ID
      
      await apiRequest.patch(`/api/PurchaseReceipts/${id}/approve`, {
        ApprovedBy: approverId,
        ApprovalRemark: remark.value
      })
      
      ElMessage.success('审核采购到货单成功')
      fetchPurchaseReceipts()
    }
  } catch (error) {
    if (error === 'cancel') return
    const errorMsg = error.response?.data?.message || '审核采购到货单失败'
    ElMessage.error(errorMsg)
    console.error('Failed to approve purchase receipt:', error)
  }
}

// 导出采购到货单
const exportReceipts = () => {
  // 实现导出功能
  ElMessage.info('导出功能待实现')
}

// 初始化数据
const initData = async () => {
  try {
    await Promise.all([
      fetchPurchaseReceipts(),
      fetchSuppliers(),
      fetchPurchaseOrders(),
      fetchMaterials(),
      fetchWarehouses()
    ])
  } catch (error) {
    console.error('Initialization failed:', error)
  }
}

// 页面加载时执行
onMounted(() => {
  initData()
})
</script>

<template>
  <common-layout title="采购到货单">
    <template #header-buttons>
      <div class="buttons">
        <ElButton type="primary" @click="openDialog('create')">
          <ElIcon><Plus /></ElIcon>
          创建采购到货单
        </ElButton>
        <ElButton @click="exportReceipts">
          <ElIcon><Download /></ElIcon>
          导出
        </ElButton>
      </div>
    </template>

    <template #search-form>
      <el-form :inline="true" :model="searchParams" class="search-form">
        <el-form-item label="到货单编号" style="width: 260px;">
          <ElInput v-model="searchParams.receiptCode" placeholder="请输入到货单编号" />
      </el-form-item>
      <el-form-item label="采购订单编号" style="width: 260px;">
        <ElInput v-model="searchParams.purchaseOrderCode" placeholder="请输入采购订单编号" />
      </el-form-item>
      <el-form-item label="供应商" style="width: 260px;">
        <SupplierSelect v-model="searchParams.supplierId" placeholder="请选择供应商" @change="handleSearchSupplierChange" />
      </el-form-item>
      <el-form-item label="状态" style="width: 260px;">
        <ElSelect v-model="searchParams.status" placeholder="请选择状态">
          <ElOption v-for="(label, key) in statusMap" :key="key" :label="label" :value="key" />
        </ElSelect>
      </el-form-item>
      <el-form-item label="到货日期" style="width: 260px;">
        <ElDatePicker
          v-model="searchParams.startDate"
          type="date"
          placeholder="开始日期"
          style="margin: 0 10px;"
        />
        <ElDatePicker v-model="searchParams.endDate" type="date" placeholder="结束日期" />
      </el-form-item>
      <el-form-item>
        <ElButton type="primary" @click="handleSearch">
          <ElIcon><Search /></ElIcon>
          搜索
        </ElButton>
        <ElButton @click="handleReset">
          <ElIcon><Refresh /></ElIcon>
          重置
        </ElButton>
      </el-form-item>
    </el-form>
  </template>

  <template #data-content>
    <!-- 采购到货单列表 -->
    <ElTable :data="purchaseReceipts" style="width: 100%" v-loading="loading">
      <ElTableColumn prop="receiptCode" label="到货单编号" width="180" />
      <ElTableColumn prop="purchaseOrderCode" label="采购订单编号" width="180" />
      <ElTableColumn prop="supplierName" label="供应商" width="200" />
      <ElTableColumn prop="receiptDate" label="到货日期" width="180" />
      <ElTableColumn prop="status" label="状态" width="100" :formatter="formatStatus" />
      <ElTableColumn prop="createdBy" label="创建人" width="120" />
      <ElTableColumn label="操作" width="200" fixed="right">
        <template #default="scope">
          <ElButton type="primary" size="small" @click="viewReceiptDetail(scope.row.id)">
            <ElIcon><InfoFilled /></ElIcon>
            详情
          </ElButton>
          <ElButton size="small" @click="openDialog('update', scope.row)">
            <ElIcon><Edit /></ElIcon>
            编辑
          </ElButton>
          <ElButton type="danger" size="small" @click="handleDelete(scope.row.id)">
            <ElIcon><Delete /></ElIcon>
            删除
          </ElButton>
          <ElButton type="success" size="small" v-if="scope.row.status === 0" @click="handleApprove(scope.row.id)">
            <ElIcon><Check /></ElIcon>
            审核
          </ElButton>
        </template>
      </ElTableColumn>
    </ElTable>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="fetchPurchaseReceipts"
        @current-change="fetchPurchaseReceipts"
      />
    </div>
    </template>
  </common-layout>

    <!-- 创建/编辑采购到货单对话框 -->
    <ElDialog v-model="dialogVisible" :title="dialogType === 'create' ? '创建采购到货单' : '编辑采购到货单'" width="900px">
      <ElForm :model="currentReceipt" label-width="120px">
        <ElFormItem label="到货单编号" prop="receiptCode">
          <ElInput v-model="currentReceipt.receiptCode" placeholder="系统自动生成" :disabled="dialogType === 'update'" />
        </ElFormItem>
        <ElFormItem label="采购订单" prop="purchaseOrderId" required>
          <ElSelect v-model="currentReceipt.purchaseOrderId" placeholder="请选择采购订单" @change="handlePurchaseOrderChange" filterable clearable>
            <template v-if="purchaseOrders.length > 0">
              <ElOption v-for="order in purchaseOrders" :key="order.id" :label="`${order.orderNo} (${order.supplierName})`" :value="order.id" />
            </template>
            <template v-else>
              <ElOption label="无采购订单数据" value="" disabled />
            </template>
          </ElSelect>
        </ElFormItem>
        <ElFormItem label="供应商" prop="supplierId">
          <SupplierSelect v-model="currentReceipt.supplierId" placeholder="请选择供应商" @change="handleSupplierChange" />
        </ElFormItem>
        <ElFormItem label="到货日期" prop="receiptDate">
          <ElDatePicker v-model="currentReceipt.receiptDate" type="date" placeholder="请选择到货日期" />
        </ElFormItem>
        <ElFormItem label="入库仓库" prop="warehouseId">
          <ElSelect v-model="currentReceipt.warehouseId" placeholder="请选择入库仓库">
            <ElOption v-for="warehouse in warehouses" :key="warehouse.id" :label="warehouse.warehouseName" :value="warehouse.id" />
          </ElSelect>
        </ElFormItem>
        <ElFormItem label="备注" prop="remark">
          <ElInput v-model="currentReceipt.remark" type="textarea" placeholder="请输入备注信息" />
        </ElFormItem>

        <!-- 到货明细 -->
        <ElFormItem>
          <div style="margin-bottom: 10px; display: flex; justify-content: flex-end;">
            <ElButton type="primary" @click="addReceiptItem">
              <ElIcon><Plus /></ElIcon>
              添加明细
            </ElButton>
          </div>
          <ElTable :data="currentReceipt.items" style="width: 100%">
            <ElTableColumn prop="lineNo" label="行号" width="60" />
            <ElTableColumn label="物料" width="200">
              <template #default="scope">
                <MaterialSelect v-model="scope.row.materialId" placeholder="请选择物料" @change="(value) => handleMaterialChange(scope.row, value)" />
              </template>
            </ElTableColumn>
            <ElTableColumn prop="materialName" label="物料名称" width="150" />
            <ElTableColumn prop="specification" label="规格型号" width="150" />
            <ElTableColumn prop="unit" label="单位" width="80" />
            <ElTableColumn prop="purchaseQuantity" label="采购数量" width="100" />
            <ElTableColumn prop="receiptQuantity" label="到货数量" width="100">
              <template #default="scope">
                <ElInput v-model="scope.row.receiptQuantity" type="number" min="0" />
              </template>
            </ElTableColumn>
            <ElTableColumn prop="qualifiedQuantity" label="合格数量" width="100">
              <template #default="scope">
                <ElInput v-model="scope.row.qualifiedQuantity" type="number" min="0" />
              </template>
            </ElTableColumn>
            <ElTableColumn prop="unqualifiedQuantity" label="不合格数量" width="100">
              <template #default="scope">
                <ElInput v-model="scope.row.unqualifiedQuantity" type="number" min="0" />
              </template>
            </ElTableColumn>
            <ElTableColumn prop="unqualifiedReason" label="不合格原因" width="150">
              <template #default="scope">
                <ElInput v-model="scope.row.unqualifiedReason" placeholder="请输入不合格原因" />
              </template>
            </ElTableColumn>
            <ElTableColumn label="操作" width="80" fixed="right">
              <template #default="scope">
                <ElButton type="danger" size="small" @click="removeReceiptItem(scope.$index)">
                  <ElIcon><Delete /></ElIcon>
                  删除
                </ElButton>
              </template>
            </ElTableColumn>
          </ElTable>
        </ElFormItem>
      </ElForm>
      <template #footer>
        <ElButton @click="dialogVisible = false">取消</ElButton>
        <ElButton type="primary" @click="saveReceipt">确定</ElButton>
      </template>
    </ElDialog>

    <!-- 详情对话框 -->
    <ElDialog v-model="detailDialogVisible" title="采购到货单详情" width="900px">
      <div class="detail-container">
        <div class="detail-section">
          <div class="info-row">
            <div class="info-label">到货单编号：</div>
            <div class="info-value">{{ currentReceipt.receiptCode }}</div>
          </div>
          <div class="info-row">
            <div class="info-label">采购订单号：</div>
            <div class="info-value">{{ currentReceipt.purchaseOrderCode }}</div>
          </div>
          <div class="info-row">
            <div class="info-label">供应商：</div>
            <div class="info-value">{{ currentReceipt.supplierName }}</div>
          </div>
          <div class="info-row">
            <div class="info-label">到货日期：</div>
            <div class="info-value">{{ currentReceipt.receiptDate }}</div>
          </div>
          <div class="info-row">
            <div class="info-label">入库仓库：</div>
            <div class="info-value">{{ currentReceipt.warehouseName }}</div>
          </div>
          <div class="info-row">
            <div class="info-label">状态：</div>
            <div class="info-value">{{ statusMap[currentReceipt.status] }}</div>
          </div>
          <div class="info-row">
            <div class="info-label">创建人：</div>
            <div class="info-value">{{ currentReceipt.createdBy }}</div>
          </div>
          <div class="info-row">
            <div class="info-label">创建时间：</div>
            <div class="info-value">{{ currentReceipt.createdTime }}</div>
          </div>
          <div class="info-row">
            <div class="info-label">备注：</div>
            <div class="info-value">{{ currentReceipt.remark }}</div>
          </div>
        </div>

        <!-- 详情明细 -->
        <div class="detail-section">
          <h3>到货明细</h3>
          <ElTable :data="currentReceipt.items" style="width: 100%">
            <ElTableColumn prop="lineNo" label="行号" width="60" />
            <ElTableColumn prop="materialCode" label="物料编码" width="120" />
            <ElTableColumn prop="materialName" label="物料名称" width="150" />
            <ElTableColumn prop="specification" label="规格型号" width="150" />
            <ElTableColumn prop="unit" label="单位" width="80" />
            <ElTableColumn prop="purchaseQuantity" label="采购数量" width="100" />
            <ElTableColumn prop="receiptQuantity" label="到货数量" width="100" />
            <ElTableColumn prop="qualifiedQuantity" label="合格数量" width="100" />
            <ElTableColumn prop="unqualifiedQuantity" label="不合格数量" width="100" />
            <ElTableColumn prop="unqualifiedReason" label="不合格原因" width="150" />
          </ElTable>
        </div>
      </div>
      <template #footer>
        <ElButton @click="detailDialogVisible = false">关闭</ElButton>
      </template>
    </ElDialog>
</template>

<style scoped>
.app-container {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.title {
  font-size: 18px;
  font-weight: bold;
}

.buttons {
  display: flex;
  gap: 10px;
}

.search-form {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 5px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.detail-container {
  padding: 10px;
}

.detail-section {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 5px;
}

.info-row {
  display: flex;
  margin-bottom: 10px;
}

.info-label {
  width: 120px;
  font-weight: bold;
}

.info-value {
  flex: 1;
}
</style>